package com.pinganfu.mock.server;

import java.io.BufferedReader;  
import java.io.DataInputStream;  
import java.io.DataOutputStream;  
import java.io.InputStreamReader;  
import java.io.PrintWriter;
import java.net.ServerSocket;  
import java.net.Socket;  
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.json.JSONObject;
import org.json.XML;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

import com.pinganfu.mock.control.trendsData;
import com.pinganfu.mock.model.ScoketMouldEntity;
import com.pinganfu.mock.service.IScoketMouldService;
  
public class server4 {  
	
	
	@Resource
	private IScoketMouldService iScoketMouldService;
	
    public static final int PORT = 8081;//监听的端口号     
      
    public static void main(String[] args) {    
        System.out.println("端口号：8081，服务器启动...\n");    
        server4 server = new server4();    
        server.init();    
    }    
    
    public void init() {    
        try {    
            ServerSocket serverSocket = new ServerSocket(PORT);    
            while (true) {    
                // 一旦有堵塞, 则表示服务器与客户端获得了连接    
                Socket client = serverSocket.accept();    
                // 处理这次连接    
                new HandlerThread(client);    
            }    
        } catch (Exception e) {    
            System.out.println("服务器异常: " + e.getMessage());    
        }    
    }    
    
    private class HandlerThread implements Runnable {    
        private Socket socket;    
        public HandlerThread(Socket client) {    
            socket = client;    
            new Thread(this).start();    
        }    
    
        public void run() {   
        	String serviceName;
        	String ssString ="未知异常";
            try {    
                // 读取客户端数据    
            	BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
                String line = input.readLine();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException  
                // 处理客户端数据    
                System.out.println("客户端发过来的内容:" + line);    
                // 向客户端回复信息    
                PrintWriter out = new PrintWriter(socket.getOutputStream());    
               // System.out.print("请输入:\t");    
                // 发送键盘输入的一行    
                //String s = new BufferedReader(new InputStreamReader(System.in)).readLine();    
                
                String ss = line.substring(0,line.indexOf(" "));
                serviceName = "http://10.59.33.49:8081/"+ss;
                String dataUp  = line.substring(line.indexOf("<"));
                
                if(dataUp.indexOf("<")>=0){
    				try {
    					XMLSerializer xmlSerializer = new XMLSerializer();
    					JSON j = xmlSerializer.read(dataUp); 
    					
    					dataUp = j.toString();
    				} catch (Exception e) {
    					// TODO: handle exception
    					System.out.println("===============传入参数异常=================");
    					dataUp="";
    				}
    				
    				
    			}else{
    				if (dataUp.indexOf("\n")>=0) {
    					String test1 = dataUp.replace("\n","");
    					dataUp = test1;
    				}
    			}
    			
    			 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    			 String request_time = df.format(new Date());
    			// System.out.println(request_time +"\t服务器端得到服务名：" + serviceName.toString());
    		     System.out.println(request_time +"\t服务器端得到数据：" + dataUp.toString());
    		        
    			 ScoketMouldEntity entity = new ScoketMouldEntity();
    				
    				entity.setUrl(serviceName);
    				entity.setPort("8081");
    				
    				
    				
    				//拿到模板
    				String data  =  iScoketMouldService.getScoketMouldByName(entity);
                
    				
    				if(data.indexOf("<")>=0){
    					try {
    						XMLSerializer xmlSerializer = new XMLSerializer();
    						System.out.println(1);
    						JSON j = xmlSerializer.read(data); 
    						
    						data = j.toString();
    					} catch (Exception e) {
    						data = "";
    					}
    					
    				}
    				System.out.println("2222222222222222222222");
    				
    				if (!dataUp.equals("") && !data.equals("")) {
    					try {
    						trendsData trData = new trendsData();
    						ssString = trData.json(dataUp, data);
    						
    						JSONObject jsonObj=new JSONObject(ssString);
    						 
    						ssString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT>"+XML.toString(jsonObj)+"</ROOT>";
    						
    					} catch (Exception e) {
    						System.out.println("===============返回参数异常=================");
    						ssString = "未知异常";
    						
    					}
    					
    				}else {
    					ssString ="未知异常";
    				}
                
                
                
                
                
                out.println(ssString);    
                out.close();    
                input.close();    
            } catch (Exception e) { 
            	
                System.out.println("服务器 run 异常: " + ssString);    
            } finally {    
                if (socket != null) {    
                    try {    
                        socket.close();    
                    } catch (Exception e) {    
                        socket = null;    
                        System.out.println("服务端 finally 异常:" + ssString);    
                    }    
                }    
            }   
        }    
    }    
}
